package subumbo.demo.view.firework {
	import flash.events.Event;
	import flash.filters.BlurFilter;
	import flash.filters.ColorMatrixFilter;
	import flash.geom.Rectangle;
	
	import mx.controls.Button;
	import mx.core.Application;
	import mx.core.UIComponent;
	import mx.events.ResizeEvent;
	
	import org.flintparticles.common.events.EmitterEvent;
	import org.flintparticles.twoD.particles.ParticleCreator2D;
	import org.flintparticles.twoD.renderers.mxml.PixelRenderer;

	public class Firework extends UIComponent {
		
		private var _renderer:PixelRenderer;
		private var _index:int;
		
		public function Firework() {
			_renderer= new PixelRenderer(new Rectangle(0,0, 1000, 500));
			_renderer.addFilter( new BlurFilter( 2, 2,1 ) );
	      	_renderer.addFilter( new ColorMatrixFilter( [ 1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0.93,0 ] ) );
	      	addChild( _renderer );
	      	addEventListener(Event.ADDED_TO_STAGE, added, false, 0 ,true);
	      	
	      
		}
		
		private function added(e:Event):void {
			stage.addEventListener(ResizeEvent.RESIZE, resize, false, 0 , true);
			resize(null);
		}
		
		private function resize(e:Event):void {
			x = Application.application.width * .5 - 500;
			y = Application.application.height * .5 - 250;
		}	
		
		public function start():void {
			_index = 0;
			var emitter:TextEmitter = TextEmitter(_renderer.emitters[_index]);
			emitter.start();
			emitter.addEventListener( EmitterEvent.EMITTER_EMPTY, restart, false, 0, true );
		}
		
		public function addEmitter(emitter:TextEmitter, _x:Number, _y:Number):void {
			emitter.x = _x;
			emitter.y = _y;
			_renderer.addEmitter(emitter);	
			
		}
		
		private function restart(e:EmitterEvent):void {
			var emitter:TextEmitter = TextEmitter(e.target);
			emitter.removeEventListener( EmitterEvent.EMITTER_EMPTY, restart );
			emitter.stop();
			_index++;
			if(_index == _renderer.emitters.length) _index = 0;
			emitter = TextEmitter(_renderer.emitters[_index]);
			emitter.start();
			emitter.addEventListener( EmitterEvent.EMITTER_EMPTY, restart, false, 0, true );
		}
		
		public function dispose():void {
			var i:int = _renderer.emitters.length;
			var emitter:TextEmitter;
			while( --i > -1 ) {
				emitter = TextEmitter(_renderer.emitters[i]);
				emitter.stop();
				ParticleCreator2D(emitter.particleFactory).clearAllParticles();
				_renderer.removeEmitter(emitter);
				emitter.removeEventListener( EmitterEvent.EMITTER_EMPTY, restart);
			}	
			emitter = null;
			removeChild(_renderer);
			_renderer = null;
		}
	}
}